from unittest import result
from OLD.applications import exce
import config

 
def getuser():
    cursor = config.db.cursor()
    sql = "select * from user order by id desc"
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        data = []
        for row in results:
            user = {}
            user['id'] = row[0]
            user['name'] = row[1]
            user['age'] = row[2]
            data.append(user)
        return data
    except:
        return "数据不存在"

def getuserbyid(id):
    cursor = config.db.cursor()
    sql = "select * from user where id = {} ".format(id)
    try:   
        cursor.execute(sql)
        result = cursor.fetchone()
        data = {
            'id':result[0],
            'user':result[1],
            'age':result[2]
        }
        return data
    except:
        return '数据不存在'

def adduser(name,age):
    cursor = config.db.cursor()
    sql = "insert into user (name,age) values ('{}','{}') ".format(name,age)
    try:
        cursor.execute(sql)
        return '添加成功'
    except:
        return '添加失败'


def deleteuser(id):
    cursor = config.db.cursor()
    sql = "delete from user where id = {} ".format(id)
    try:
        cursor.execute(sql)
        return '删除成功'
    except:
        return '删除失败'


def updateuser(id,name,age):
    cursor = config.db.cursor()
    try:
        sql = "update user set name = '{}' , age = '{}' where id = '{}'".format(name,age,id)
        cursor.execute(sql)
        return '更新成功'
    except:
        return '更新失败'